


<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }" @click.native="clearStorage">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="openSetRole">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="rolesList"
        border
        style="width: 100%">
        <!-- 展开权限列表 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
            class="rolesRow"
            :class="{rolesBoderBottom: id1 === 0}"
            v-for="(item1, id1) in scope.row.children"
            :key="item1.id"
            >
              <!-- 一级标题 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级标题及三级权限 -->
              <el-col :span="19">
                <el-row class="rolesRow"
                :class="{rolesBoderBottom: id2 === 0}"
                v-for="(item2, id2) in item1.children"
                :key="item2.id"
                >
                <!-- 二级标题 -->
                  <el-col :span="6">
                    <el-tag closable type="success"
                    @close="removeRightsById(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级标题 -->
                  <el-col :span="18">
                    <el-tag closable type="warning"
                    v-for="(item3) in item2.children"
                    :key="item3.id"
                    @close="removeRightsById(scope.row, item3.id)"
                    >
                    {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="openRoleInfo(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteRole(scope.row)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-share" @click="setRoleRights(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分配权限对话框 -->
      <el-dialog
        title="权限分配"
        :visible.sync="roleVisible"
        width="50%"
        @close="dialogClose"
        >
        <!-- 树形控件 -->
        <el-tree
        :data="rightsList"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        highlight-current
        node-key="id"
        :default-checked-keys="checkKeys"
        ref="treeRefs"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRights">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="setRoleVisible"
        width="50%"
        @close="resetRoleForm"
        >
        <el-form
        label-width="80px"
        :model="roleForm"
        :rules="roleFormRules"
        ref="roleRefs"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item  label="角色描述">
            <el-input v-model="roleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">添加</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色对话框 -->
      <el-dialog
        title="编辑角色"
        :visible.sync="editRoleVisible"
        width="50%"
        >
        <el-form
        label-width="80px"
        :model="editRoleForm"
        :rules="roleFormRules"
        ref="role"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item  label="角色描述">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoleInfo">提交</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      roleVisible: false,
      setRoleVisible: false,
      editRoleVisible: false,
      rightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      checkKeys: [],
      roleId: '',
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      editRoleForm: {},
      roleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    clearStorage () {
      window.sessionStorage.setItem('activePath', '')
      this.$router.go(0)
    },
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
    },
    removeRightsById (role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '删除权限', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        // this.getRoleList()
        role.children = res.data
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async setRoleRights (role) {
      // 获取所有权限的数据
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightsList = res.data
      this.getLastKeys(role, this.checkKeys)
      this.roleVisible = true
    },
    getLastKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLastKeys(item, arr)
      })
    },
    dialogClose () {
      this.checkKeys = []
    },
    async addRights () {
      const keys = [
        ...this.$refs.treeRefs.getCheckedKeys(),
        ...this.$refs.treeRefs.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.getRoleList()
      this.roleVisible = false
    },
    openSetRole () {
      this.setRoleVisible = true
    },
    saveRoleInfo () {
      this.$refs.roleRefs.validate(async (valid) => {
        if (!valid) return this.$message.error('提交信息有误')
        const { data: res } = await this.$http.post('roles', this.roleForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        this.getRoleList()
      })
    },
    resetRoleForm () {
      this.$refs.roleRefs.resetFields()
    },
    openRoleInfo (row) {
      this.editRoleVisible = true
      this.editRoleForm = row
    },
    editRoleInfo () {
      this.$refs.role.validate(async (valid) => {
        if (!valid) return this.$message.error('提交信息有误')
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.id, {
          id: this.editRoleForm.id,
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('修改角色信息失败')
        this.$message.success('修改角色信息成功')
        this.getRoleList()
        this.editRoleVisible = false
      })
    },
    deleteRole (row) {
      this.$confirm('此操作将永久删除该角色信息, 是否继续?', '删除角色', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        const { data: res } = await this.$http.delete('roles/' + row.id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getRoleList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="less" scope>
.rolesRow {
  padding: 10px;
  border-top: 1px solid #ccc;
  display: flex;
  align-items: center;
}
.rolesBoderBottom {
  border-top: none;
}
.el-tag {
  margin: 5px;
}
</style>